package com.rrqs.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.litesuits.http.request.content.multi.StringPart;
import com.rrqs.MessageEvents;
import com.rrqs.activity.adapter.ExceptionDialogAdapter;
import com.rrqs.activity.adapter.MyMainAsyncTask;
import com.rrqs.activity.common.Common;
import com.rrqs.activity.common.Const;
import com.rrqs.activity.data.GetAbnormalReasonBean;
import com.rrqs.activity.data.MainNumData;
import com.rrqs.activity.data.NewVersionData;
import com.rrqs.activity.data.PostAbnormalBean;
import com.rrqs.activity.data.QiangDanData;
import com.rrqs.activity.data.UserData;
import com.rrqs.frame.JsonProcessHelper;
import com.rrqs.frame.MyApplication;
import com.rrqs.net.AsyncHttpClient;
import com.rrqs.net.HttpResponseListener;
import com.rrqs.receiver.ExampleUtil;
import com.rrqs.util.Utils;
import com.rrqs.utils.JsonUtils;
import com.rrqs.views.CmlRequestBody;
import com.rrqs.views.ShowMsgDialog;
import com.rrqs.views.SlidingMenu;
import com.umeng.update.UmengUpdateAgent;
import com.zadtek.xmqishi.R;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.rrqs.activity.common.Const.TOURL;

public class MainActivity extends TabActivity implements
        OnCheckedChangeListener, OnClickListener, ExceptionDialogAdapter.onRecyclerItemClickerListener {

    private SlidingMenu mMenu;

    private long exitTime = 0;

    private TabHost tabhost;
    private RadioGroup tab_radio;
    private RadioButton radio_newrw;    //新任务
    public static RadioButton radio_goqh, radio_gops; // 新任务,待取货,配送中

    private RadioGroup pushlay; // 是否开工
    private RadioButton workbut, orderno, order_busy; // 开工1,收工2,忙碌3

    private Intent Ordernew, Orderqh, Orderps;

    private TextView ordoverid, usermoney, userset, paihbang, leaderboard, my_attendance, notification_center, abnormal_reporting, map; // 已完成的任务,账户余额,设置,排行榜、地图
    private TextView myname, myphone; // 姓名,手机
    private ImageView myicon, iv_detail;
    private RelativeLayout mymsglay;
    private TextView sygordoverid;    //已完成的跑腿任务

    private SharedPreferences sp;

    private Handler mHandler;
    private QiangDanData sumcout;
    private UserData qsdata;    //骑士信息

    private String tagclose = "1";    //默认开工

    private NewVersionData versdata;    //新版本的信息
    private AlertDialog alertDialog;
    private View exception_dialog;
    private EditText inputExceptionReason;
    private RecyclerView exceptionReasonList;
    private TextView confirmReportBtn;
    private ExceptionDialogAdapter adapter;
    private List<String> ids;

    /**
     * 上传进度
     */
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    //上传失败
//                    Toast.makeText(FullInfoActivity.this, "系统异常", Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    //上传成功
                    String responseData = msg.obj.toString();
                    Log.i("yudan", msg.arg2 + "上传图片==" + responseData);
                    try {
                        JSONObject object = new JSONObject(responseData);
                        String pic = object.getString("url");//返回码
                        changeIcon(pic);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case 4:
                    Bundle bundle = msg.getData();
                    String ret = bundle.getString("ret");
                    String message = bundle.getString("msg");
                    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    private void changeIcon(final String pic) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String uid = getSharedPreferences(Const.PREF_NAME,
                        Context.MODE_PRIVATE).getString("uid", "");
                FormBody.Builder builder = new FormBody.Builder()
                        .add("ince", "user_picture")
                        .add("emp_id", uid)
                        .add("img", pic);
                RequestBody requestBody = builder.build();
                Request request = new Request.Builder().url(TOURL).header("Content-Type", "application/x-www-form-urlencoded").post(requestBody).build();
                try {
                    Response response = new OkHttpClient().newCall(request).execute();
                    if (response.isSuccessful()) {
                        String responseData = response.body().string();
                        Log.i("yudan", "修改头像:" + responseData);
                        JSONObject object = new JSONObject(responseData);
                        String ret = object.getString("status");//返回码
                        String msg = "";
                        if (ret.equals("1")) {
                            msg = object.getString("sucess");
                        } else {
                            msg = object.getString("fail");
                        }
                        Message message = new Message();
                        message.what = 4;
                        Bundle data = new Bundle();
                        data.putString("ret", ret);
                        data.putString("msg", msg);
                        message.setData(data);
                        handler.sendMessage(message);
                    } else {
                        throw new IOException("Unexpected code" + response);
                    }
                } catch (IOException e) {
                    Log.i("yudan", "发布商品:" + e);
                    e.printStackTrace();
                } catch (JSONException e) {
                    Log.i("yudan", "发布商品:" + e);
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_main);

        // 友盟检查版本
//		com.umeng.common.Log.LOG = true;
        // 如果想程序启动时自动检查是否需要更新， 把下面两行代码加在Activity 的onCreate()函数里。
        UmengUpdateAgent.setUpdateOnlyWifi(false);
        UmengUpdateAgent.update(this);

        mMenu = (SlidingMenu) findViewById(R.id.menuid);
        tab_radio = (RadioGroup) findViewById(R.id.tab_radio);
        tab_radio.setOnCheckedChangeListener(this);
        tabhost = getTabHost();

        radio_newrw = (RadioButton) findViewById(R.id.radio_newrw);
        radio_goqh = (RadioButton) findViewById(R.id.radio_goqh);
        radio_gops = (RadioButton) findViewById(R.id.radio_gops);

        pushlay = (RadioGroup) findViewById(R.id.pushlay);
        workbut = (RadioButton) findViewById(R.id.workbut);
        orderno = (RadioButton) findViewById(R.id.orderno);
        order_busy = (RadioButton) findViewById(R.id.order_busy);

        Ordernew = new Intent(this, OrdernewActivity.class)
                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        tabhost.addTab(tabhost
                .newTabSpec("Ordernew")
                .setIndicator(
                        "",
                        getResources().getDrawable(
                                R.drawable.ordermenu_selector))
                .setContent(Ordernew));

        Orderqh = new Intent(this, OrderqhActivity.class)
                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        tabhost.addTab(tabhost
                .newTabSpec("Orderqh")
                .setIndicator(
                        "",
                        getResources().getDrawable(
                                R.drawable.ordermenu_selector_last))
                .setContent(Orderqh));

        Orderps = new Intent(this, OrderpsActivity.class)
                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        tabhost.addTab(tabhost
                .newTabSpec("Orderps")
                .setIndicator(
                        "",
                        getResources().getDrawable(
                                R.drawable.ordermenu_selector_last))
                .setContent(Orderps));

        tabhost.setCurrentTab(0);

        ordoverid = (TextView) findViewById(R.id.ordoverid);
        ordoverid.setOnClickListener(this);
        usermoney = (TextView) findViewById(R.id.usermoney);
        usermoney.setOnClickListener(this);
        userset = (TextView) findViewById(R.id.userset);
        userset.setOnClickListener(this);

        paihbang = (TextView) findViewById(R.id.paihbang);
        paihbang.setOnClickListener(this);

        abnormal_reporting = (TextView) findViewById(R.id.abnormal_reporting);
        abnormal_reporting.setOnClickListener(this);
        leaderboard = (TextView) findViewById(R.id.leaderboard);
        leaderboard.setOnClickListener(this);
        my_attendance = (TextView) findViewById(R.id.my_attendance);
        my_attendance.setOnClickListener(this);
        notification_center = (TextView) findViewById(R.id.notification_center);
        notification_center.setOnClickListener(this);

        sygordoverid = (TextView) findViewById(R.id.sygordoverid);
        sygordoverid.setOnClickListener(this);

        map = (TextView) findViewById(R.id.map);
        map.setOnClickListener(this);

        initViews();

        mHandler = new Handler() {
            @SuppressLint("NewApi")
            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                super.handleMessage(msg);
                switch (msg.what) {
                    case Const.STATE_START_SUCCESS: // 获取数量成功
                        sumcout = (QiangDanData) msg.obj;
                        String status = sumcout.getStatus();
                        if (status != null && status.equals("1")) {
                            String xincount = sumcout.getNeworder();
                            String noget = sumcout.getNoget();
                            String nosend = sumcout.getNosend();
                            radio_goqh.setText("待取货(" + noget + ")");
                            radio_gops.setText("配送中(" + nosend + ")");
                        }
                        break;
                    case Const.STATE_START_ERROR:
                        // Common.DisplayToast(MainActivity.this, "通信失败,请检查网络!", 2);
                        break;
                    case Const.STATE_GETNUM_SUCC:    //获取骑士信息成功
                        qsdata = (UserData) msg.obj;
                        String qsstatus = qsdata.getStatus();
                        if (qsstatus != null && qsstatus.equals("1")) {
                            writeSp(qsdata);    //先存入缓存
                            myname.setText(qsdata.getRealname());
                            myphone.setText(qsdata.getPhone());
                            Glide.with(MainActivity.this).load(qsdata.getUrl()).placeholder(R.drawable.user_icon).into(myicon);
                            String close = qsdata.getClose();
                            setWordcheck(close);
                            Const.uid = qsdata.getUid();
                        }
                        break;
                    case Const.STATE_SETQS_OPEN:    //设置骑士开收工成功
                        QiangDanData data = (QiangDanData) msg.obj;
                        String setstatus = data.getStatus();
                        if (setstatus != null && setstatus.equals("1")) {
                            //设置成功后,存入缓存
                            sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
                            Editor editor = sp.edit();
                            editor.putString("close", tagclose);
                            editor.commit();
                            if ("1".equals(tagclose)) {
                                new AlertDialog.Builder(MainActivity.this)
                                        .setMessage("文明出行，请遵守交通规则!")
                                        .setPositiveButton("确定", null).show();
                            } else if("2".equals(tagclose)){
                                new AlertDialog.Builder(MainActivity.this)
                                        .setMessage("收工状态不接订单")
                                        .setPositiveButton("我要开工",
                                                new DialogInterface.OnClickListener() {
                                                    public void onClick(DialogInterface dialog2, int which) {

                                                        tagclose = "1";
                                                        setWordcheck(tagclose);
                                                    }
                                                }).setNegativeButton("知道了", null).show();
                            } else if("3".equals(tagclose)){
                                new AlertDialog.Builder(MainActivity.this)
                                        .setMessage("忙碌状态下仅可接收人工派单")
                                        .setPositiveButton("我要开工",
                                                new DialogInterface.OnClickListener() {
                                                    public void onClick(DialogInterface dialog2, int which) {

                                                        tagclose = "1";
                                                        setWordcheck(tagclose);
                                                    }
                                                }).setNegativeButton("知道了", null).show();
                            }


                        } else {
                            sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
                            String close = sp.getString("close", "");
                            setWordcheck(close);
                            new AlertDialog.Builder(MainActivity.this)
                                    .setMessage("忙碌状态下仅可接收人工派单")
                                    .setPositiveButton("我要开工",
                                            new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog2,
                                                                    int which) {

                                                    tagclose = "1";
                                                    setWordcheck(tagclose);
//                                                    new MyMainAsyncTask(MainActivity.this, mHandler).execute(
//                                                            "setclose", tagclose);

                                                }
                                            }).setNegativeButton("知道了", null).show();
                        }
                        break;
                    case Const.STATE_SETQS_FAIL:    //设置骑士开收工失败
                        sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
                        String close = sp.getString("close", "");
                        setWordcheck(close);
                        break;
                    case Const.STATE_GETVERSIONOK:    //获取新版本信息
                        versdata = (NewVersionData) msg.obj;
                        if (versdata != null) {
                            //检测新版本
                            checkVersion(MainActivity.this, versdata.getVersion());
                        }
                        break;
                }
            }
        };

        pushlay.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup arg0, int arg1) {
                // TODO Auto-generated method stub
                RadioButton checkbut = (RadioButton) findViewById(pushlay.getCheckedRadioButtonId());
                tagclose = checkbut.getTag().toString();
                new MyMainAsyncTask(MainActivity.this, mHandler).execute(
                        "setclose", tagclose);
            }
        });

        //获取用户信息
        if (Common.isNetworkConnected(MainActivity.this)) {
            new MyMainAsyncTask(MainActivity.this, mHandler)
                    .execute("getversion");
            new MyMainAsyncTask(MainActivity.this, mHandler)
                    .execute("getqsmsg");
        }

    }

    //检测新版本及更新
    private boolean checkVersion(Context context, String version) {
        boolean hasnew = false;
        PackageInfo pi = null;
        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);
            if (pi != null) {
//				String versioname = pi.versionName;
                int versioncode = pi.versionCode;
                if (version != null && !version.equals("")) {
                    if (versioncode < Integer.parseInt(version)) {//有新的版本需要更新
                        showDialog();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return hasnew;
    }

    //弹出更新的版本
    private void showDialog() {
        if (versdata != null) {
            String note = versdata.getNote();
            ShowMsgDialog MyDialog = new ShowMsgDialog(MainActivity.this, "发现新版本", note) {
                // 选择修改
                @Override
                public void doConfirmUp() {
                    String filename = versdata.getDown_url();
                    if (filename != null && !filename.equals("")) {
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(filename));
                        startActivity(intent);
                    }
                    dismiss();
                }
            };
            MyDialog.show();
        }
    }

    // 设置用户的信息
    public void initViews() {
        sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
        String uname = sp.getString("uname", "");
        String phone = sp.getString("phone", "");
        String close = sp.getString("close", "");

        myname = (TextView) findViewById(R.id.myname);
        myphone = (TextView) findViewById(R.id.myphone);
        myicon = (ImageView) findViewById(R.id.myicon);

        iv_detail = (ImageView) findViewById(R.id.iv_detail);
        mymsglay = (RelativeLayout) findViewById(R.id.mymsglay);
        myname.setText(uname);
        myphone.setText(phone);
        setWordcheck(close);
        myicon.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                requestPermissions();
            }
        });

        iv_detail.setOnClickListener(this);

        mymsglay.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this, PersonalInformationActivity.class));
            }
        });
        mymsglay.setOnClickListener(this);
    }

    //设置用户开收工
    public void setWordcheck(String close) {
        if (close.equals("1")) {    //开工
            workbut.setChecked(true);
            orderno.setChecked(false);
            order_busy.setChecked(false);
        } else if (close.equals("2")) {    //收工
            orderno.setChecked(true);
            workbut.setChecked(false);
            order_busy.setChecked(false);
        } else {
            orderno.setChecked(false);
            workbut.setChecked(false);
            order_busy.setChecked(true);
        }
    }

    // 将用户信息写入缓存中
    private void writeSp(UserData userdata) {
        sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
        Editor editor = sp.edit();
        editor.putString("uid", userdata.getUid());
        editor.putString("uname", userdata.getRealname());
        editor.putString("phone", userdata.getPhone());
        editor.putString("account", userdata.getAccount());
        editor.putString("close", userdata.getClose());
        editor.putString("qsstatus", userdata.getQsstatus());
        editor.commit();
    }

    // 点击事件
    public void toggleMenu(View view) {
        mMenu.toggle();
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        // TODO Auto-generated method stub
        // 获取数量
        getmymsgCount();
        switch (checkedId) {
            case R.id.radio_newrw: // 新任务
                this.tabhost.setCurrentTabByTag("Ordernew");
                break;
            case R.id.radio_goqh: // 待取货
                this.tabhost.setCurrentTabByTag("Orderqh");
                break;
            case R.id.radio_gops: // 配送中
                this.tabhost.setCurrentTabByTag("Orderps");
                break;
        }
    }

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        switch (arg0.getId()) {
            case R.id.ordoverid: // 已完成的任务
                startActivity(new Intent(this, OrderOverNewActivity.class));
//                startActivity(new Intent(this, OrderOverActivity.class));
                break;
            case R.id.usermoney: // 账户余额
                startActivity(new Intent(this, UserMoneyActivity_.class));
                break;
            case R.id.userset: // 账户余额
                Intent intentset = new Intent(this, SettingActivity.class);
                startActivity(intentset);
                break;
            case R.id.sygordoverid:    //已完成的跑腿任务
                startActivity(new Intent(this, SygOrderOverActivity.class));
                break;
            case R.id.paihbang:    //我的统计
                startActivity(new Intent(this, MytjFragment.class));
                break;
            case R.id.map:    //配送热力图
                startActivity(new Intent(this, UserAddressMap.class));
                break;
            case R.id.abnormal_reporting:    //异常上报
                new getAbnormalReasonTask().execute();
                break;
            case R.id.leaderboard:    //排行榜
                startActivity(new Intent(this, PaihFragment.class));
                break;
            case R.id.my_attendance:    //我的考勤
                startActivity(new Intent(this, MyCheckFragment.class));
                break;
            case R.id.notification_center:    //通知中心
                startActivity(new Intent(this, TongzhiCenterActivity.class));

                break;
            case R.id.iv_detail:    //我的详情
            case R.id.mymsglay:    //我的详情
                if (!TextUtils.isEmpty(Const.uid)) {
                    startActivity(new Intent(this, MeDetailActivity.class));
                }
                break;
        }
    }

    @Override
    public void onRecyclerItemClick(int position, List<String> ids) {
        this.ids = ids;
    }

    public class getAbnormalReasonTask extends AsyncTask<String, String, GetAbnormalReasonBean> {

        @Override
        protected GetAbnormalReasonBean doInBackground(String... strings) {
            GetAbnormalReasonBean bean = JsonProcessHelper.jsonProcess_get_abnormal_reason();
            if (bean != null) {
                return bean;
            }
            return null;
        }

        @Override
        protected void onPostExecute(GetAbnormalReasonBean getAbnormalReasonBean) {
            super.onPostExecute(getAbnormalReasonBean);
            if (getAbnormalReasonBean != null) {
                showExceptionDialog(getAbnormalReasonBean.getList());
            }
        }
    }

    private void showExceptionDialog(List<GetAbnormalReasonBean.ListBean> data) {
        alertDialog = new AlertDialog.Builder(MainActivity.this).create();
        alertDialog.setCancelable(true);
        exception_dialog = LayoutInflater.from(this).inflate(R.layout.exception_dialog, null);
        inputExceptionReason = exception_dialog.findViewById(R.id.inputExceptionReason);
        exceptionReasonList = exception_dialog.findViewById(R.id.exceptionReasonList);
        confirmReportBtn = exception_dialog.findViewById(R.id.confirmReportBtn);
        confirmReportBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                String input_str = inputExceptionReason.getText().toString();
                if (TextUtils.isEmpty(input_str)) {
                    if (ids == null || ids.size() == 0) {
                        Toast.makeText(MainActivity.this, "请输入或选择异常原因", Toast.LENGTH_LONG).show();
                        return;
                    } else {
                        String ids_str = "";
                        for (int i = 0; i < ids.size(); i++) {
                            ids_str += "," + ids.get(i);
                        }
                        new MainActivity.postAbnormalTask().execute(Const.uid, ids_str.substring(1), "", "0");
                    }
                } else {
                    if (ids == null || ids.size() == 0) {
                        new MainActivity.postAbnormalTask().execute(Const.uid, "", input_str, "0");
                    } else {
                        String ids_str = "";
                        for (int i = 0; i < ids.size(); i++) {
                            ids_str += "," + ids.get(i);
                        }
                        new MainActivity.postAbnormalTask().execute(Const.uid, ids_str.substring(1), input_str, "0");
                    }
                }
                alertDialog.dismiss();
            }
        });
        adapter = new ExceptionDialogAdapter(MainActivity.this, data);
        adapter.setListener(this);
        exceptionReasonList.setLayoutManager(new GridLayoutManager(this, 3));
        exceptionReasonList.setAdapter(adapter);
        alertDialog.show();

        Window window = alertDialog.getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.gravity = Gravity.CENTER;
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        layoutParams.width = dm.widthPixels * 4 / 5;
        layoutParams.height = dm.heightPixels * 5 / 6;
        layoutParams.x = 0;
        window.setAttributes(layoutParams);
        window.setContentView(exception_dialog);
    }

    public class postAbnormalTask extends AsyncTask<String, String, PostAbnormalBean> {

        @Override
        protected PostAbnormalBean doInBackground(String... strings) {
            PostAbnormalBean bean = JsonProcessHelper.jsonProcess_post_abnormal(strings[0], strings[1], strings[2], strings[3]);
            if (bean != null) {
                return bean;
            }
            return null;
        }

        @Override
        protected void onPostExecute(PostAbnormalBean postAbnormalBean) {
            super.onPostExecute(postAbnormalBean);
            if (postAbnormalBean != null) {
                Toast.makeText(MainActivity.this, postAbnormalBean.getMsg(), Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        // 获取数量
        getmymsgCount();
        getnumbei();
    }

    // 得到任务列表数据
    public void getmymsgCount() {
        if (Common.isNetworkConnected(MainActivity.this)) {
            sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
            String uid = sp.getString("uid", "");
            if (uid != null && !uid.equals("")) {
                new MyMainAsyncTask(MainActivity.this, mHandler).execute("getsum");
            }
        }
    }


    /**
     * 捕捉返回事件按钮
     */

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (event.getAction() == KeyEvent.ACTION_DOWN
                    && event.getRepeatCount() == 0) {
                this.exitApp();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (event.getAction() == KeyEvent.ACTION_DOWN
                    && event.getRepeatCount() == 0) {
                // 响应事件的具体代码
                this.exitApp();
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    /**
     * 退出程序
     */
    private void exitApp() {
        // 判断2次点击事件时间
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT)
                    .show();
            exitTime = System.currentTimeMillis();
        } else {
            MyApplication.getInstace().exit();
        }
    }

    // for receive customer msg from jpush server
    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.rrqs.activity.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                String messge = intent.getStringExtra(KEY_MESSAGE);
                String extras = intent.getStringExtra(KEY_EXTRAS);
                StringBuilder showMsg = new StringBuilder();
                showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                if (!ExampleUtil.isEmpty(extras)) {
                    showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                }
            }
        }
    }

    private void requestPermissions() {
        if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
            photo();
        else {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED && grantResults[2] == PackageManager.PERMISSION_GRANTED)
                photo();
            else
                Toast.makeText(getApplicationContext(), "权限被拒绝", Toast.LENGTH_SHORT).show();
        }
    }

    private void photo() {
        Glide.get(this.getApplicationContext()).clearMemory();
        Matisse.from(MainActivity.this)
                .choose(MimeType.ofImage())//图片类型
                .countable(false)//true:选中后显示数字;false:选中后显示对号
                .maxSelectable(1)//可选的最大数
                .capture(true)//选择照片时，是否显示拍照
                .captureStrategy(new CaptureStrategy(true, "com.zadtek.xmshangjia"))//参数1 true表示拍照存储在共有目录，false表示存储在私有目录；参数2与 AndroidManifest中authorities值相同，用于适配7.0系统 必须设置
                .imageEngine(new GlideEngine())//图片加载引擎
                .forResult(0);//
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == RESULT_OK) {
            File file = new File(Matisse.obtainPathResult(data).get(0));
            if (file.exists()) {
                Bitmap bitmap = BitmapFactory.decodeFile(Matisse.obtainPathResult(data).get(0));
                myicon.setImageBitmap(bitmap);
                upLoadImage("img", file);
            }

        }

    }

    /**
     * 上传图片
     */
    private void upLoadImage(final String fileName, final File file) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
                MultipartBody.Builder builder = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart(fileName, ".jpg", fileBody)
                        .addFormDataPart("ince", "arr");
                RequestBody requestBody = builder.build();
                Request.Builder request = new Request.Builder().url("http://xmshop.zadtek.com/mobile/Api/index")
                        .header("Content-Type", "application/x-www-form-urlencoded").post(new CmlRequestBody(requestBody) {
                            @Override
                            public void loading(long current, long total, boolean done) {
                            }
                        });
                OkHttpClient client = new OkHttpClient();
                client.newBuilder().readTimeout(60000, TimeUnit.MILLISECONDS).build().newCall(request.build()).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.i("yudan", "上传图片" + e.toString());
                        upLoadImage(fileName, file);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (!response.isSuccessful() || response == null || response.body() == null) {
                            sendMessage(1, 0, 0, "");
                        } else {
                            //返回值处理
                            sendMessage(2, 100, 0, response.body().string());
                        }
                    }

                });
            }
        }).start();
    }

    private void sendMessage(int what, long current, long total, String msg) {

        Message message = Message.obtain();
        message.what = what;
        message.arg1 = (int) current;
        message.obj = msg;
        handler.sendMessage(message);
    }

    @Subscribe
    public void onEventMainThread(final String event) {
        if (Utils.LOGINELSEWHERE.equals(event)) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    if (!MyApplication.getInstace().getTopActivity().contains("QsLoginActivity")) {
                        Intent intent = new Intent(MainActivity.this, QsLoginActivity_.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        startActivity(intent);
                        finish();
                    }
                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(MessageEvents message) {
        if (message.getEventsType().equals("mainshuaxin")) {
            Log.i("CYX", "刷新首页数字");
            getnumbei();
        }
    }

    private void getnumbei() {
        AsyncHttpClient httpClient = new AsyncHttpClient(com.rrqs.util.MyApplication.getInstace());

        SharedPreferences sp = com.rrqs.util.MyApplication.getInstace().getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
        String uid = sp.getString("uid", "");

        com.litesuits.http.request.content.multi.MultipartBody body = new com.litesuits.http.request.content.multi.MultipartBody();
        body.addPart(new StringPart("emp_id", uid));
        body.addPart(new StringPart("ince", "get_order_num"));
        httpClient.post("http://xmpc.zadtek.com/mobile/Qs/index", body, new HttpResponseListener() {
            @Override
            public void onFailure(Throwable error) {
                super.onFailure(error);

            }

            @SuppressWarnings("unchecked")
            @Override
            public void onSuccess(String status, String result) {
                super.onSuccess(status, result);
                try {
                    Log.i("CYX", "首页获取数量" + result);
                    JSONObject jsonObject = new JSONObject(result);
                    Log.i("CYX", "首页获取数量" + jsonObject);
                    MainNumData resp = JsonUtils.json2Class(result, MainNumData.class);
                    if (resp.getRet() == 200) {
                        radio_newrw.setText("新任务（" + resp.getData().getNew_num() + "）");
                        radio_goqh.setText("待取货（" + resp.getData().getWait_num() + "）");
                        radio_gops.setText("配送中（" + resp.getData().getSending_num() + "）");
                    } else {
                        Toast.makeText(MainActivity.this, resp.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }
}
